package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import org.apache.xmlbeans.impl.jam.JamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    /**
     * C端用户登录接口
     * @param dto
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO dto) {
//        1.通过微信的接口服务，获得当前用于的openId
//        构建map集合放数据，下面可以抽象成一个方法
        HashMap<String, String> map = new HashMap<>();
        map.put("appId", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", dto.getCode());
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

//        转成JSON对象
        JSONObject jsonObject = JSON.parseObject(json);
//        通过JSON对象获取openId
        String openid = jsonObject.getString("openid");

//        2.判断该用户openId是否为空
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
//        3.判断是否为新用户
        User user = userMapper.selectByOpenId(openid);
//        4.如果是新的，将其数据放入到用户表中
        if (user == null) {
           user =  User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertNewOpenId(user);
        }
//        5.返回该用户对象
        return user;
    }
}
